package opencv.service.algorithms;

import java.awt.Rectangle;

import com.googlecode.javacv.jna.cxcore.IplImage;

/**
 * @author Aakash Polra
 */
public class FaceTracker extends FaceDetection {

	private Rectangle facePosition;
	private long lastRunTime;
	
	public static final float MAX_ALLOWED_SPEED = 3.0f;	// pixels per second
	
	
	public FaceTracker(String faceCascadePath, String eyesCascadePath) {
		super(faceCascadePath, eyesCascadePath);
	}
	
	
	@Override
	public void run(IplImage img1, IplImage img2) {
		// run face detection
		super.run(img1, img2);
		
		//
		if (lastRunTime <= 0)
		{
			// TODO
		}
		
		Rectangle nearest = null;
		long distanceSq = Long.MAX_VALUE;
		
		
		if (getLastFoundFaces().size() == 0) {
			return;
		} else {
			
			if (facePosition == null) {
				facePosition = getLastFoundFaces().get(0);
			}
			
			if (getLastFoundFaces().size() == 1) {
				nearest = getLastFoundFaces().get(0);
				distanceSq = ((facePosition.x - nearest.x)*(facePosition.x - nearest.x)) +
				((facePosition.y - nearest.y)*(facePosition.y - nearest.y));
			} else {
				// find nearest face
				for (Rectangle currRect : getLastFoundFaces()) {
					
					// distance between top-left edges
					long currDistanceSq = ((facePosition.x - currRect.x)*(facePosition.x - currRect.x)) +
						((facePosition.y - currRect.y)*(facePosition.y - currRect.y));
					
					// minimum distance
					if (currDistanceSq < distanceSq) {
						distanceSq = currDistanceSq;
						nearest = currRect;
					}
				}
			}
		}

		// calculate speed
		double speed = Math.sqrt(distanceSq) / (System.currentTimeMillis() - lastRunTime);
		if (speed <= MAX_ALLOWED_SPEED) {
			lastRunTime = System.currentTimeMillis();
			facePosition = nearest;
		}
	}
	
	public Rectangle getFacePosition() {
		return facePosition;
	}

}
